package com.ys.load.util;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

/**
 * 电子书下载工具栏
 * 
 * @author yusong
 * @date 20241104
 */
public class BooksUtil {

	/**
	 * 生成uuid
	 * 
	 * @return
	 */
	public static String UUIDGenerator() {
		UUID uuid = UUID.randomUUID();
		return uuid.toString();
	}

	/**
	 * 生成二维码图片
	 * @param text
	 * @param width
	 * @param height
	 * @param filePath
	 */
	public static void generateQRCodeImage(String text, int width, int height, String filePath) {
		try {
			QRCodeWriter qrCodeWriter = new QRCodeWriter();
			Map<EncodeHintType, Object> hints = new HashMap<>();
			hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
			BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints);

			BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			bufferedImage.createGraphics();

			Graphics2D graphics = (Graphics2D) bufferedImage.getGraphics();
			graphics.setColor(java.awt.Color.WHITE);
			graphics.fillRect(0, 0, width, height);
			graphics.setColor(java.awt.Color.BLACK);

			for (int i = 0; i < width; i++) {
				for (int j = 0; j < height; j++) {
					if (bitMatrix.get(i, j)) {
						graphics.fillRect(i, j, 1, 1);
					}
				}
			}

			ImageIO.write(bufferedImage, "png", new File(filePath));
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
